﻿#ifndef WEATHERTOOL_H
#define WEATHERTOOL_H
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonParseError>
#include <map>
#include <QFile>
#include <QCoreApplication>
#include <QDebug>
using namespace std;
class WeatherTool{
public:
    WeatherTool(){
        //1.获取当前项目路径   +    获取json数据的路径
        QString fileName = QCoreApplication::applicationDirPath();
        fileName+="/citycode-2019-08-23.json";
        //fileName+="/../../wea/citycode-2019-08-23.json";
        //2.打开文件  +  读取文件 +关闭文件
        QFile file(fileName);
        file.open(QIODevice::ReadOnly|QIODevice::Text);
        QByteArray jsonfile = file.readAll();
        file.close();
        //3.读取json数据
        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonfile,NULL);//NULL指向的是错误，这里先不管
        //4.读取json的列表
        QJsonArray cityMessage = jsonDoc.array();
        for(auto eachCityMeaasge:cityMessage){   //eachCityMeaasge是一个{}
            QString code = eachCityMeaasge.toObject().value("city_code").toString();  //取{}中key为city_code的value
            QString city = eachCityMeaasge.toObject().value("city_name").toString();
            //省份的code是空的，所以城市代码长度大于0的都可以添加的map中
            if(code.size()>0){
                  cityMapCode.insert(pair<QString,QString>(city,code));
            }

        }

    }
    QString operator[](const QString& city){
        map<QString,QString>::iterator it = cityMapCode.find(city);
        if(it == cityMapCode.end()){
            it = cityMapCode.find(city + u8"省");
        }
        if(it == cityMapCode.end()){
            it = cityMapCode.find(city + u8"市");
        }
        if(it == cityMapCode.end()){
            it = cityMapCode.find(city + u8"镇");
        }
        if(it == cityMapCode.end()){
            it = cityMapCode.find(city + u8"县");
        }
        if(it!=cityMapCode.end()){
            return it->second;
        }
        return "000000000";
    }
public:
    map<QString,QString> cityMapCode; //city对应的code

};

#endif // WEATHERTOOL_H
